iT邦幫忙

2025 iThome 鐵人賽

DAY 24
0
生成式 AI

Chatting with ChatGPT——一天學習一題Leetcode系列 第 24

LeetCode 21. Merge Two Sorted Lists(合併兩個有序鏈表)

  • 分享至 

  • xImage
  •  

今天真是匆匆忙忙、連滾帶爬的一天呢...
好啦不管,今天的題目大意是:
要你把兩個「已經排序好的鏈結串列」合併成一個新的排序好的串列。
就是說假設你有:
List1: 1 → 2 → 4
List2: 1 → 3 → 4
那你要把它們合成一個:1 → 1 → 2 → 3 → 4 → 4
重點是要保持排序(由小到大),不能只是單純把兩串接起來

class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        // 建立一個「虛擬頭節點」(dummy),方便後續操作
        ListNode dummy = new ListNode(-1);

        // 用 current 來追蹤新串列目前的位置
        ListNode current = dummy;

        // 當兩個串列都還沒走完時,就持續比較
        while (list1 != null && list2 != null) {

            // 如果 list1 的值比較小
            if (list1.val < list2.val) {
                current.next = list1;  // 把 list1 的這個節點接到結果串列後面
                list1 = list1.next;    // list1 往下一個節點移動
            } else {
                current.next = list2;  // 否則接上 list2 的節點
                list2 = list2.next;    // list2 往下一個節點移動
            }

            current = current.next; // 結果串列也往後移動一格
        }

        // 當其中一個串列走完後,直接把另一串剩下的節點接上
        if (list1 != null) current.next = list1;
        if (list2 != null) current.next = list2;

        // 回傳「虛擬頭節點的下一個」才是真正的開頭
        return dummy.next;
    }
}

上一篇
週三之LeetCode 83. Remove Duplicates from Sorted List
下一篇
3. Longest Substring Without Repeating Characters
系列文
Chatting with ChatGPT——一天學習一題Leetcode30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言